/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shellCommands;

import Sessions.EcomAdminRemote;
import Sessions.EcomCustomersRemote;
import entityBeans.Category;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author SOGOBA
 */
public class CategoryCommand implements InterShell {
    ContextCommande cxtCmd;

    public CategoryCommand(ContextCommande ContextCommand){
          cxtCmd =  ContextCommand;
    }
    @Override
    public Commands getName() {
          return Commands.category;
    }

    @Override
    public String getShortDescription() {
        String description = "Category management\n";
        description += "\t  : [without args] ........................................list all category \n";
        description += "\t  : -add [name] .............................................create a new category \n";
        return description;
    }
    
    @Override
    public void execute(String cmd,EcomAdminRemote ecomAdmin,EcomCustomersRemote ecomCust) throws Exception {    
        StringTokenizer st = new StringTokenizer(cmd, " ");
        // Ignore cmd
        st.nextToken();

        // sans argument, on liste les magasins
        if (st.countTokens() == 0) {
            List<Category> lesCat = ecomCust.getAllCat();
           if (cxtCmd.getVar("output").equals("XML")){
            System.out.println(getXML(lesCat));
            }
            else{
                 System.out.println(getText(lesCat));
                }
        } // prise en compte des arguments
        else {
            String option = st.nextToken();

            // adding
            if (option.equals("-add")) {
                if (st.countTokens() == 1) {
                   String name= st.nextToken();
                   ecomAdmin.createCat(name);
                   System.out.println("Your category was created successfully");
                } else {
                    System.out.println("Command is not avalaible");
                }
            }
        }
         
}

    @SuppressWarnings("CallToThreadDumpStack")
 public String getXML(List<Category> lesCat){
        String xmlString="";
        try {
            // Create Document factory
            DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
            // Create document
            DocumentBuilder constructeur = fabrique.newDocumentBuilder();
            // Read a file XML with DOM
            File xml = new File("XMLDocument.xml");
            Document document = constructeur.parse(xml);
            // Cr�ation de l'arborescence du DOM
            Element racine = document.getDocumentElement();
           racine.appendChild(document.createComment("Dysplay all category "));
            Element cart = document.createElement("categories");
            racine.appendChild(cart);
            // Get all products
            for (Category cat : lesCat) {
                Element c = document.createElement("category");
                cart.appendChild(c);
                Element catId = document.createElement("reference");
                catId.setTextContent(cat.getIdCategory().toString());
                c.appendChild(catId);
                Element name = document.createElement("name category");
                name.setTextContent(cat.getNameCategory());
                c.appendChild(name);
              
            }
                DOMSource domSource = new DOMSource(document);
                StringWriter writer = new StringWriter();
                StreamResult result = new StreamResult(writer);
                TransformerFactory tf = TransformerFactory.newInstance();
                Transformer transformer = tf.newTransformer();
                transformer.transform(domSource, result);
                xmlString = writer.toString();
        }
        catch (IOException | ParserConfigurationException ex) {
            Logger.getLogger(CategoryCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    catch(Exception e){
            e.printStackTrace();
          }
    return xmlString;
}


public String getText (List<Category> lesCat){
    String textString="List of all category of product \n";
    for (Category cat : lesCat){
       textString+="reference : "+ cat.getIdCategory() +"name : "+ cat.getNameCategory()+ "\n";
    }
    return textString;
 }

}
